﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThornProcessor : MonoBehaviour
{
    private const int m_MAX_THORN_COUNT = 1;

    [SerializeField]
    private Thorn m_thornModel;
    private List<Thorn> m_thornList;
    private Sprite[] m_thornTextures;

    private void Awake()
    {
        m_thornModel.gameObject.SetActive(false);
    }
    private void OnEnable()
    {
        if (m_thornTextures == null)
            m_thornTextures = Resources.LoadAll<Sprite>("Images/Thron");
        if (m_thornList == null)
            m_thornList = new List<Thorn>();
    }
    private void Update()
    {
        if (m_thornList.Count < m_MAX_THORN_COUNT)
        {
            var thorn = m_CreateThorn(MapSelfAdaptaionTool.gameRect.D_L, MapSelfAdaptaionTool.gameRect.U_R);
            m_thornList.Add(thorn);
            thorn.HitSomeMonsterEvent += () => { m_thornList.Remove(thorn); };
        }
    }

    private Thorn m_CreateThorn(Vector2 pRange_D_L, Vector2 pRange_U_R)
    {
        var thorn_clone = Instantiate(m_thornModel.gameObject, this.transform, false).GetComponent<Thorn>();
        var pos_x = Random.Range(pRange_D_L.x + (pRange_U_R.x - pRange_D_L.x) * 0.1f, pRange_U_R.x - (pRange_U_R.x - pRange_D_L.x) * 0.1f);
        var pos_y = Random.Range(pRange_D_L.y + (pRange_U_R.y - pRange_D_L.y) * 0.1f, pRange_U_R.y - (pRange_U_R.y - pRange_D_L.y) * 0.1f);
        thorn_clone.SetLocalPos(new Vector2(pos_x, pos_y));
        thorn_clone.SetLocalRotate(Quaternion.Euler(new Vector3(0, 0, Random.Range(0, 360))));
        thorn_clone.SetColor(Color.white);
        var textureIndex = Random.Range(0, m_thornTextures.Length);
        thorn_clone.SetSprite(m_thornTextures[textureIndex]);
        thorn_clone.gameObject.name = "thorn(clone)" + textureIndex.ToString();
        thorn_clone.gameObject.SetActive(true);
        return thorn_clone;
    }
}
